package online.hxstart.code.concurrent.chapter05;

import java.util.LinkedList;

/**
 * @author huxing
 * @date 19-4-24 星期三 下午12:20
 * @describe
 */
public class EventQueue {

  private final int MAX;

  static class Event {}

  private final LinkedList<Event> eventQueue = new LinkedList<>();

  private static final int DEFAULT_MAX_EVENT = 10;

  public EventQueue() {
    this(DEFAULT_MAX_EVENT);
  }

  public EventQueue(int max) {
    this.MAX = max;
  }

  public void offer(Event event) {
    synchronized (eventQueue) {
      while (eventQueue.size() >= MAX) {
        try {
          console(" the queue is full");
          eventQueue.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      console(" the new event is submitted");
      eventQueue.addLast(event);
      eventQueue.notifyAll();
    }
  }

  public Event take() {
    synchronized (eventQueue) {
      while (eventQueue.isEmpty()) {
        try {
          console(" the queue is empty.");
          eventQueue.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      Event event = eventQueue.removeFirst();
      this.eventQueue.notifyAll();
      console(" the event " + event + " is handled");
      return event;
    }
  }

  private void console(String s) {
    System.out.printf("%s:%s\n", Thread.currentThread().getName(), s);
  }
}
